import platform
import os
import os.path

# global vars
build = ''
env_debug = None
env_release = None
env = None # points to env_debug or env_release depending on the build

def parse_command_line_args():
    AddOption('--build',
                  dest='build',
                  type='string',
                  nargs=1,
                  action='store',
                  help='build type (debug | release)')

    global build
    build = GetOption('build')
    if build != 'release' and build != 'debug':
        print 'missing build argument'
        return False
    return True

def setup_environment():
    global env_debug
    global env_release
    global env

    #setup vars
    debug_vars = Variables()
    release_vars = Variables()

    debug_vars.Add('build_dir', 'build directory', 'build_debug')
    debug_vars.Add('build_type', 'build type', 'debug')
    release_vars.Add('build_dir', 'build directory', 'build_release')
    release_vars.Add('build_type', 'build type', 'release')

    # create envs
    env_debug = Environment(variables = debug_vars, ENV = os.environ)
    env_release = Environment(variables = release_vars, ENV = os.environ)

    env_debug.Append(CPPPATH = ['src'])
    env_release.Append(CPPPATH = ['src'])

    if platform.system() != 'Windows':
        env_debug.Append(LIBS = ['m'])
        env_release.Append(LIBS = ['m'])

    env_debug.Append(CCFLAGS = '-Od')
    env_debug.Append(CCFLAGS = '-D_DEBUG')
    env_debug.Append(CCFLAGS = '-D_CONSOLE')
    env_debug.Append(CCFLAGS = '-D_UNICODE')
    env_debug.Append(CCFLAGS = '-DUNICODE')
    env_release.Append(CCFLAGS = '-Ot')
    env_release.Append(CCFLAGS = '-DNDEBUG')

    # select env variant
    if build == 'debug':
        env = env_debug
    elif build == 'release':
        env = env_release

# setup build environment and export it so it will be visible for all Sconscripts
if parse_command_line_args() == False:
    exit(0)

setup_environment()
Export('env')
Export('env_debug')
Export('env_release')
Export('build')

env.Program('test_${build_type}', source = Glob('src/*.c') + Glob('src_test/*.c'))